﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Interactivity;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
using System.Diagnostics;
using System.Windows.Input;


namespace Clipping.Utils
{
    public class SelectDataGridRowOnMouseDownBehavior : Behavior<DataGrid>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.PreviewMouseDown += new System.Windows.Input.MouseButtonEventHandler(AssociatedObject_PreviewMouseDown);
        }


        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.PreviewMouseDown -= new System.Windows.Input.MouseButtonEventHandler(AssociatedObject_PreviewMouseDown);

        }



        private void AssociatedObject_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            object item = GetElementFromPoint((ItemsControl)sender, e.GetPosition((ItemsControl)sender));
        }

        private object GetElementFromPoint(ItemsControl itemsControl, Point point)
        {
            UIElement element = itemsControl.InputHitTest(point) as UIElement;
            while (element != null)
            {
                if (element == itemsControl)
                    return null;
                object item = itemsControl.ItemContainerGenerator.ItemFromContainer(element);
                if (!item.Equals(DependencyProperty.UnsetValue))
                    return item;
                var p = VisualTreeHelper.GetParent(element);
                if (p is UIElement)
                    element = (UIElement)p;
                else
                    break;
            }
            return null;
        }
    }
}
